package electionView;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Semaphore;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import electionCtrl.Election;
import electionCtrl.Vote;

public class VoteReviewGui extends ElectionGui
{
	public enum Button
	{
		CAST_VOTE,BACK;
		
		public String toString()
		{
			String str = super.toString();
			return str.substring(0,1) + str.substring(1).toLowerCase().replaceAll("_", " ");
		}
	};
	
	private JPanel listOfVotes;
	private JButton castVoteButton;
	private JButton backButton;
	private Button action;
	
	public VoteReviewGui(Election election, Vote[] votes, Semaphore semaphore)
	{
		super(election, new JFrame("Review your votes"), semaphore);
		
		this.mainFrame.setLayout(new FlowLayout());
		
		this.action = null;
		
		String voteString = "Your selections are as follows:\n\n";
		for(Vote v : votes)
		{
			if(v == null)
			{
				continue;
			}
			voteString += "For " + v.candidate.seat + ", you voted for: " + v.candidate.name + " (" + v.candidate.party + ")." + "\n";
		}
		voteString += "\nIf you can confirm that you wish to vote for each candidate in each seat, press \"Cast vote\".  Otherwise, press \"Back\" to change your selections.";
		JTextArea list = new JTextArea(voteString, 40, 115);
		list.setEditable(false);
		list.setDragEnabled(false);
		list.setLineWrap(true);
		list.setWrapStyleWord(true);
//		list.setFocusable(false);
		
		this.listOfVotes = new JPanel();
		this.listOfVotes.setLayout(new BorderLayout());
		this.listOfVotes.add(list,BorderLayout.CENTER);
		
		this.castVoteButton = new JButton(Button.CAST_VOTE.toString());
		this.castVoteButton.addActionListener(new CastVoteButtonListener());
		
		this.backButton = new JButton(Button.BACK.toString());
		this.backButton.addActionListener(new BackButtonListener());
		
		this.mainFrame.add(this.listOfVotes);
		this.mainFrame.add(this.castVoteButton);
		this.mainFrame.add(this.backButton);
		this.mainFrame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
	}
	
	private class CastVoteButtonListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent e)
		{
			action = Button.CAST_VOTE;
			releaseResources();
		}
	}
	
	private class BackButtonListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent e)
		{
			action = Button.BACK;
			releaseResources();
		}
	}
	
	public Button waitForAction() throws InterruptedException
	{
		this.acquireResources();
		Button b = this.action;
		this.action = null;
		return b;
	}
}
